package request

import (
	"gitee.com/z930255076/go-ext/constants"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"github.com/gofiber/fiber/v2"
	"reflect"
	"strings"
)

type GameService struct {
	Error    bool
	ErrorMsg string
}

// GetParams 获取传参
func GetParams(c *fiber.Ctx, params interface{}) error {
	// 使用时需要调整结构体传输类型（json -> query）
	if c.Method() == fiber.MethodGet {
		if err := c.QueryParser(params); err != nil && string(c.Body()) != "" {
			return fiber.NewError(constants.NormalError, "入参 JSON 解析失败")
		}
	} else if c.Method() == fiber.MethodPost {
		// 获取传参
		if err := c.BodyParser(params); err != nil && string(c.Body()) != "" {
			return fiber.NewError(constants.NormalError, "入参 JSON 解析失败")
		}
	}

	// 参数验证
	validate := validator.New()
	validate.RegisterTagNameFunc(func(field reflect.StructField) string {
		return field.Tag.Get("comment")
	})
	err := validate.Struct(params)
	if err != nil {
		// 验证器注册翻译器
		zhCh := zh.New()
		uni := ut.New(zhCh)
		trans, _ := uni.GetTranslator("zh")
		trErr := zh_translations.RegisterDefaultTranslations(validate, trans)
		if trErr != nil {
			return fiber.NewError(constants.NormalError, "验证器注册翻译器错误")
		}

		// 组装错误信息
		var sliceErrs []string
		for _, err := range err.(validator.ValidationErrors) {
			sliceErrs = append(sliceErrs, err.Translate(trans))
		}

		return fiber.NewError(constants.NormalError, strings.Join(sliceErrs, "；"))
	}

	return nil
}
